﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace Utils
{
    public sealed class DataHelper
    {
        public static List<T> ToList<T>(DataTable dt) where T : new()
        {
            using (dt)
            {
                if (Equals(null, dt))
                    return null;

                var prList = new List<PropertyInfo>();

                Array.ForEach(typeof(T).GetProperties(), p =>
                {
                    if (dt.Columns.IndexOf(p.Name) > -1)
                    {
                        prList.Add(p);
                    }
                });

                var list = new List<T>();
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var t = new T();
                    prList.ForEach(
                        p => p.SetValue(t, Equals(DBNull.Value, dt.Rows[i][p.Name]) ? null : dt.Rows[i][p.Name], null));
                    list.Add(t);
                }

                return list;
            }
        }

        public static List<T> ToList<T>(IDataReader reader) where T : new()
        {
            using (reader)
            {
                if (Equals(null, reader))
                    return null;

                var list = new List<T>();
                var columsStr = string.Empty;
                var prList = new List<PropertyInfo>();
                for (var i = 0; i < reader.FieldCount; i++)
                {
                    columsStr += reader.GetName(i) + ",";
                }
                Array.ForEach(typeof(T).GetProperties(), p =>
                {
                    if (p.Name.IndexOf(columsStr, StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        prList.Add(p);
                    }
                });
                while (reader.Read())
                {
                    var t = new T();
                    foreach (var property in prList)
                    {
                        property.SetValue(t, Equals(DBNull.Value, reader[property.Name]) ? null : reader[property.Name],
                            null);
                    }
                }

                if (!reader.IsClosed)
                    reader.Close();

                return list;
            }
        }

    }
}
